package com.glq1218.common.model;

import com.glq1218.common.constant.HttpStatus;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serial;
import java.io.Serializable;

/**
 * @author glq1218
 */

@Data
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "统一响应类")
public class Result<T> implements Serializable {

    @Serial
    private static final long serialVersionUID = -5002110469085248362L;

    /**
     * 成功
     */
    public static final Integer SUCCESS = HttpStatus.SUCCESS;

    /**
     * 失败
     */
    public static final Integer FAIL = HttpStatus.ERROR;

    @Schema(description = "状态码")
    private Integer code;
    @Schema(description = "信息")
    private String msg;
    @Schema(description = "数据")
    private T data;

    public static <T> Result<T> ok() {
        return restResult(SUCCESS, "操作成功", null);
    }

    public static <T> Result<T> ok(String msg) {
        return restResult(SUCCESS, msg, null);
    }

    public static <T> Result<T> ok(T data) {
        return restResult(SUCCESS, "操作成功", data);
    }

    public static <T> Result<T> ok(String msg, T data) {
        return restResult(SUCCESS, msg, data);
    }

    public static <T> Result<T> fail() {
        return restResult(FAIL, "操作失败", null);
    }

    public static <T> Result<T> fail(String msg) {
        return restResult(FAIL, msg, null);
    }

    public static <T> Result<T> fail(T data) {
        return restResult(FAIL, "操作失败", data);
    }

    public static <T> Result<T> fail(T data, String msg) {
        return restResult(FAIL, msg, data);
    }

    public static <T> Result<T> fail(Integer code, String msg) {
        return restResult(code, msg, null);
    }

    private static <T> Result<T> restResult(Integer code, String msg, T data) {
        Result<T> apiResult = new Result<>();
        apiResult.setCode(code);
        apiResult.setMsg(msg);
        apiResult.setData(data);
        return apiResult;
    }

    public static <T> Boolean isError(Result<T> ret) {
        return !isSuccess(ret);
    }

    public static <T> Boolean isSuccess(Result<T> ret) {
        return Result.SUCCESS == ret.getCode();
    }
}
